package cn.ty.znsz.Login;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.Ret;

import cn.ty.znsz.common.interceptor.PostInterceptor;
import cn.ty.znsz.common.interceptor.RequestInterceptor;

/**
 * 所有 sql 与业务逻辑写在 Service 中，不要放在 Model 中，更不
 * 要放在 Controller 中，养成好习惯，有利于大型项目的开发与维护
 */

@Path(value = "/login")
public class LoginController extends Controller{
	
	@Inject
	LoginService ls;
	
	/**
	 * 登录页
	 */
	@Clear(RequestInterceptor.class)
	public void index() {
		render("index.html");
	}
	/**
	 * 生成验证码
	 */
	@Clear(RequestInterceptor.class)
	public void captcha() {
		renderCaptcha();
	}
	/**
	 * 注册账号
	 */
	@Clear(RequestInterceptor.class)
	public void reg() {
		render("register.html");
	}
	/**
	 * 登录
	 */
	@Clear(RequestInterceptor.class)
	@Before({LoginValidator.class,PostInterceptor.class})
	public void doLogin() {
		Ret ret = ls.doLogin(getPara("loginName"), getPara("password"));
		if (ret.isOk()) {
			setCookie("jznsz", ret.getStr("token"), 7 * 24 * 3600, true);
			ret.set("returnUrl", "/");
		}
		renderJson(ret);
	}
	/**
	 * 注册
	 */
	@Clear(RequestInterceptor.class)
	@Before({PostInterceptor.class,RegisterValidator.class})
	public void doRegister() {
		Ret ret = ls.doRegister(getPara("userName"),getPara("loginName"), getPara("password"));
		if (ret.isOk()) {
			ret.set("returnUrl", "/login");
		}
		renderJson(ret);
	}
	/**
	 * 退出登录
	 */
	public void loginOut() {
		removeCookie("jznsz");
		redirect("/login");
	}
}
